package com.seed.launcher.listener;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.AudioManager;

import androidx.annotation.Keep;
import androidx.annotation.NonNull;

/**
 * 音量监听
 * 最大值不固定需获取{@link AudioManager#getStreamMaxVolume(int)}
 * @author xct
 * create on: 2022/8/30 11:18
 */
@Keep
public class VolumeListener extends BroadcastReceiver implements Registerable {

    private static final String TAG = "VolumeListener";

    private static final String ACTION_VOLUME_CHANGED = "android.media.VOLUME_CHANGED_ACTION";
    private static final String EXTRA_VOLUME_STREAM_TYPE = "android.media.EXTRA_VOLUME_STREAM_TYPE";

    private final Context mContext;
    private final OnValueChangedCallback mListener;

    public VolumeListener(Context context, @NonNull OnValueChangedCallback listener) {
        mContext = context;
        mListener = listener;
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        int streamType = intent.getIntExtra(EXTRA_VOLUME_STREAM_TYPE, -1);
        if (streamType == AudioManager.STREAM_MUSIC) {
            handleStream(context, streamType);
        }
    }

    private void handleStream(Context context, int streamType) {
        AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
        int streamVolume = audioManager.getStreamVolume(streamType);
        int streamMaxVolume = audioManager.getStreamMaxVolume(streamType);
        if (streamMaxVolume <= 0) {
            streamMaxVolume = 1;
        }
        float ratio = 1f * streamVolume / streamMaxVolume;
        ratio = Math.max(0, Math.min(ratio, 1));
        mListener.onChanged(ratio);
    }

    @Override
    public void register() {
        IntentFilter intentFilter = new IntentFilter(ACTION_VOLUME_CHANGED);
        mContext.registerReceiver(this, intentFilter);
        //主动获取
        handleStream(mContext,AudioManager.STREAM_MUSIC);
    }

    @Override
    public void unregister() {
        mContext.unregisterReceiver(this);
    }
}
